package com.zyg.filter;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class JwtAuthorizationFilter extends OncePerRequestFilter {

    private final String jwtSecret;

    public JwtAuthorizationFilter(String jwtSecret) {
        this.jwtSecret = jwtSecret;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {
        String header = request.getHeader("Authorization");

        // 检查 Authorization Header
        //   //login接口不会被jwtAuthenticationEntryPoint捕获，即使没有token不会进入token认证失败验证
        if (header == null || !header.startsWith("Bearer ")) {
            chain.doFilter(request, response);
            return;
        }

        try {
            // 提取并解析 Token
            String token = header.replace("Bearer ", "");
            Claims claims = Jwts.parser()
                    .setSigningKey(jwtSecret)
                    .parseClaimsJws(token)
                    .getBody();

            //这个就对应String token = Jwts.builder()
            //                .setSubject(user.getUsername())   login生成token的代码获取username
            String username = claims.getSubject();

            // 将用户信息保存到 SecurityContext 中，可以在全局获取用户信息
            if (username != null) {
                UsernamePasswordAuthenticationToken authentication =
                        new UsernamePasswordAuthenticationToken(username, null, null);
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        } catch (Exception e) {
            // 处理 JWT 验证失败的情况
            SecurityContextHolder.clearContext();
            throw new RuntimeException("token error");
        }

        chain.doFilter(request, response);
    }
}
